//
//  ContentView.swift
//  XCFPSMonitor
//
//  Created by mac on 2025/2/17.
//

import SwiftUI

struct ContentView: View {
    
    @State private var currentFPS: Int = 0
    @State private var isScrolling: Bool = false
    
    var body: some View {
        VStack {
            Text("Current FPS: \(currentFPS)")
                .font(.largeTitle)
            List(0...20, id: \.self) { index in
                Text("currentIndex = \(index)")
                    .padding()
                    .background(GeometryReader { geometry in
                        Color.clear
                            .preference(key: ScrollPreferenceKey.self, value: geometry.frame(in: .global).minY)
                    })
                    .onPreferenceChange(ScrollPreferenceKey.self) { value in
                        if isScrolling {
                            triggerLag() // 在滑动时触发耗时操作
                        }
                    }
            }
            .simultaneousGesture(DragGesture().onChanged { _ in
                isScrolling = true
            }.onEnded { _ in
                isScrolling = false
            })
            Button("Trigger Lag") {
                triggerLag()
            }
            .padding()
        }
        .onAppear(perform: {
            XCFPSMonitor.shared.onUpdateFps = { fps in
                currentFPS = fps
            }
            XCFPSMonitor.shared.start()
        })
        .onDisappear(perform: {
            XCFPSMonitor.shared.stop()
        })
        .padding()
    }
    
    // 添加一个可以使页面卡顿的函数
    private func triggerLag() {
        // 在主线程中执行一个耗时的操作
        for _ in 0..<100000 {
            // 模拟耗时计算
            _ = sqrt(Double.random(in: 1...100))
        }
    }
}

// 自定义的 PreferenceKey 用于获取滚动位置
struct ScrollPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {}
}

#Preview {
    ContentView()
}
